/**
 * 
 */
package sqs.dataaccess.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import sqs.exception.HibernateAccessLayerException;

/**
 * @author kjleng
 *
 */
public class HibernateFactory {
	private static SessionFactory sessionFactory;
	public static SessionFactory buildSessionFactory() throws HibernateException {
        if (sessionFactory != null) {
            closeFactory();
        }
        return configureSessionFactory();
    }
	
	public static SessionFactory buildIfNeeded() throws HibernateAccessLayerException{
        if (sessionFactory != null) {
            
            return sessionFactory;
        }
        try {
            return configureSessionFactory();
        } catch (HibernateException e) {
            throw new HibernateAccessLayerException(e);
        }
    }
    
	public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    
    public static Session openSession() throws HibernateException {
        buildIfNeeded();
        return sessionFactory.openSession();
    }
    
    public static void closeFactory() {
        if (sessionFactory != null) {
            try {
                sessionFactory.close();
            } catch (HibernateException ignored) {
                System.out.println("Couldn't close SessionFactory!!!");
            }
        }
    }
    
    public static void close(Session session) {
        if (session != null) {
            try {
                session.close();
            } catch (HibernateException ignored) {
            	System.out.println("Couldn't close Session!!!!!");
            }
        }
    }
    
    public static void rollback(Transaction tx) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (HibernateException ignored) {
        	System.out.println("Couldn't rollback Transaction!!!!");
        }
    }
    
    private static SessionFactory configureSessionFactory() throws HibernateException {
        System.out.println("Hibernate Factory!!!!!");
    	Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        return sessionFactory;
    }
}
